<script setup lang="ts">
import VChart from 'vue-echarts'
import 'echarts'
import { computed, onMounted, ref } from 'vue'
import { getLatestColor } from '@/api/cropGrowthIndicatorsController.ts'

// 1. 修正字段名为小写 leaf
const colorData = ref<{
  sumLeafAlbinoCount: number
  sumLeafDarkGreenCount: number
  sumLeafWitheredCount: number
  sumLeafYellowingCount: number
} | null>(null)

const fetchColorData = async () => {
  try {
    const res = await getLatestColor()
    console.log('接口返回数据:', res.data)
    colorData.value = res.data.data
  } catch (error) {
    console.error('数据获取失败:', error)
    colorData.value = null
  }
}

const options = computed(() => {
  if (!colorData.value) {
    console.log('⚠️ 数据未加载或为空')
    return {
      title: { left: 'center', text: '叶片颜色分析' },
      tooltip: { trigger: 'item' },
      legend: { orient: 'vertical', left: 'left' },
      series: [{ name: '叶片颜色分布', type: 'pie', radius: ['40%', '70%'], data: [] }],
    }
  }

  // 2. 修正字段名引用
  const pieData = [
    {
      value: Number(colorData.value.sumLeafDarkGreenCount),
      name: '深绿色叶片',
    },
    {
      value: Number(colorData.value.sumLeafYellowingCount),
      name: '黄化叶片',
    },
    {
      value: Number(colorData.value.sumLeafWitheredCount),
      name: '枯萎叶片',
    },
    {
      value: Number(colorData.value.sumLeafAlbinoCount),
      name: '白化叶片',
    },
  ]
  console.log('🍕 饼图数据:', pieData)

  return {
    title: { left: 'center', text: '叶片颜色分析' },
    tooltip: { trigger: 'item' },
    legend: { orient: 'vertical', left: 'left' },
    series: [
      {
        name: '叶片颜色分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '50%'],
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }
})

onMounted(() => {
  fetchColorData()
})
</script>

<template>
  <div class="data-leaves-color-analyze">
    <a-card title="叶片颜色分析">
      <v-chart :option="options" style="height: 400px; width: 100%" />
    </a-card>
  </div>
</template>

<style scoped></style>
